<template>
  <div class="pagevue p-2">
    <!-- <div class="searchBox">
      <el-input v-model="searchInput" placeholder="请输入内容" style="width: 270px"></el-input>
      <el-button type="success" icon="el-icon-search" @click="searchClick">搜索</el-button>
      <el-button type="warning" icon="el-icon-refresh-right" @click="resetClick">重置</el-button>
    </div> -->
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="openFormClick('add')" v-hasPermi="['aiqa:model:add']">{{
              $t("commen.add") }}</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="multipleSelection.length != 1"
              @click="openFormClick('edit', multipleSelection[0])" v-hasPermi="['aiqa:model:edit']">{{ $t("commen.edit")
              }}</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multipleSelection.length == 0"
              @click="deleteClick(multipleSelection, 'arr')" v-hasPermi="['aiqa:model:remove']">{{ $t("commen.delete")
              }}</el-button>
          </el-col>
          <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar> -->
        </el-row>
      </template>
      <!-- 表格 -->
      <div class="page_table" v-loading="tableLoading">
        <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column :label="$t('modelManager.iconUrl')">
            <template #default="scope">
              <img :src="imgSrcFunc(scope.row.iconUrl)" style="width:26px" alt="" />
            </template>
          </el-table-column>
          <el-table-column prop="modelName" :label="$t('modelManager.modelName')"> </el-table-column>
          <el-table-column prop="value" :label="$t('modelManager.value')" width="80"> </el-table-column>
          <el-table-column prop="sort" :label="$t('modelManager.sort')" width="80"> </el-table-column>
          <el-table-column :label="$t('modelManager.enabled')" width="80">
            <template #default="scope">
              {{ scope.row.enabled ? $t('modelManager.enabled1') : $t('modelManager.enabled0') }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('modelManager.handle')" width="140" align="center">
            <template #default="scope">
              <el-button type="success" icon="el-icon-edit" v-hasPermi="['aiqa:model:edit']"
                @click="openFormClick('edit', scope.row)"></el-button>
              <el-button type="danger" icon="el-icon-delete" v-hasPermi="['aiqa:model:remove']"
                @click="deleteClick(scope.row, 'obj')"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="block" style="margin-top: 12px;">
        <el-pagination @current-change="handleCurrentChange" @size-change="handleSizeChange"
          v-model:current-page="requestStr.page" :page-sizes="[10, 20, 30, 40]" :page-size="requestStr.size"
          layout="total,  prev, pager, next,sizes" :total="requestStr.total"></el-pagination>
      </div>
    </el-card>


    <!-- 表单对话框 -->
    <el-dialog :title="titleType == 'add' ? $t('modelManager.add') : $t('modelManager.edit')" v-model="visibleDialog"
      width="500px" append-to-body :close-on-click-modal="false" @close="visibleDialogClose">
      <div>
        <el-upload class="upload-demo" drag action="" :auto-upload="false" :limit="1" :file-list="fileList"
          :on-change="uploadOnChange">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">{{ $t('modelManager.uploadText1') }}<em>{{ $t('modelManager.uploadText2')
              }}</em>
          </div>
          <div class="el-upload__tip" slot="tip">{{ $t('modelManager.uploadText3') }}</div>
        </el-upload>
        <el-form ref="formRefs" :model="form" :rules="formRules" label-width="95px">
          <el-form-item :label="$t('modelManager.modelName')" prop="modelName">
            <el-input v-model="form.modelName" :placeholder="$t('modelManager.message1')"></el-input>
          </el-form-item>
          <el-form-item :label="$t('modelManager.value')" prop="value">
            <el-input v-model="form.value" :placeholder="$t('modelManager.message2')"></el-input>
          </el-form-item>
          <el-form-item :label="$t('modelManager.roles')" prop="roles">
            <el-select v-model="form.roles" value-key="roleId" multiple :placeholder="$t('modelManager.message3')"
              style="width:365px">
              <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item"> </el-option>
            </el-select>
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item :label="$t('modelManager.enabled')" prop="enabled">
                <el-select v-model="form.enabled" :placeholder="$t('modelManager.message3')">
                  <el-option :label="$t('modelManager.enabled1')" value="1"></el-option>
                  <el-option :label="$t('modelManager.enabled0')" value="0"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('modelManager.sort')" prop="sort">
                <el-input-number v-model="form.sort" :min="1" :max="99" size="small"
                  ></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="confirmClick">{{ $t("commen.confirm")
            }}</el-button>
          <el-button @click="visibleDialogClose">{{ $t("commen.cancel") }}</el-button>
        </div>
      </template>

    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { listModel, getModel, delModel, addModel, updateModel } from '@/api/aiqa/model';
import {apiRoleQueryFreePerm} from '@/api/know/wikiApps/indexApi';
import defImages from '@/assets/images/ai3.png';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const buttonLoading = ref(false);
const searchInput = ref("")
const tableData = ref([])
const tableLoading = ref(false)
const multipleSelection = ref([])
const rowDataId = ref("")
const visibleDialog = ref(false)
const titleType = ref('')
const fileList = ref([])
const requestStr = ref({
  page: 1,
  size: 10,
  total: 0
})
const initForm:any = {
  modelName: "",
  value: "",
  enabled: "",
  sort: null,
  roles: [] 
}
const form: any = ref({...initForm})
const formRules = ref({
  modelName: [{ required: true, message: proxy.$t('modelManager.message1'), trigger: "change" }],
  value: [{ required: true, message: proxy.$t('modelManager.message2'), trigger: "change" }],
  enabled: [{ required: true, message: proxy.$t('modelManager.message3'), trigger: "change" }],
  sort: [{ required: true, message: proxy.$t('modelManager.message4'), trigger: "change" }]
  // roles: [{ required: true, message: "请选择角色范围", trigger: "change" }]
})
const roleList = ref([])

const imgSrcFunc = (img:any) =>{
  let src = img ? import.meta.env.VITE_APP_BASE_API + img : defImages;
  return src
}
// 获取角色
const apiRolesAllUnlimited = () => {
  apiRoleQueryFreePerm().then((res:any) => {
    roleList.value = res.data;
  });
}
// 分页查询
const getList = () => {
  listModel({
    pageNum: requestStr.value.page - 1,
    pageSize: requestStr.value.size,
  })
    .then((res: any) => {
      tableData.value = res.rows;
      requestStr.value.total = res.total;
    });
}
const uploadOnChange = (file: any, fileLists: any) => {
  console.log(file, fileList);
  fileList.value = fileLists;
}
// 搜索
const searchClick = () => { }
// 重置
const resetClick = () => { }
// 选中
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val;
}
//  打开编辑和新增对话框
const openFormClick = (type: any, row?: any) => {
  visibleDialog.value = true;
  titleType.value = type;
  if (type == "edit") {
    rowDataId.value = row.id;
    form.value.modelName = row.modelName;
    form.value.value = row.value;
    form.value.enabled = row.enabled ? "1" : "0";
    form.value.sort = row.sort;
    form.value.iconUrl = row.iconUrl;

    if (row.allowedRoles) {
      const rolesIds = row.allowedRoles.split(",");
      const rolesNames = row.allowedRolesName.split(",");
      const rolesArray = rolesIds.map((id, index) => ({
        id: parseInt(id, 10), // 将ID转换为整数
        name: rolesNames[index]
      }));
      form.value.roles = rolesArray;
    } else {
      form.value.roles = [];
    }
  }
}
const formRefs = ref();
//关闭对话框
const visibleDialogClose = () => {
  visibleDialog.value = false;
  rowDataId.value = "";
  titleType.value = "";
  formRefs.value.resetFields();
  // Object.keys(form.value).forEach((key) => (form.value[key] = ""));
  form.value = initForm
  form.value.roles = [];
  fileList.value = [];
}
// 对话框确定按钮
const confirmClick = () => {
  // console.log(this.form);
  formRefs.value.validate((valid) => {
    if (valid) {
      let formdata = new FormData();
      let { roles, ...newForm } = form.value;
      for (let key in newForm) {
        formdata.append(key, newForm[key]);
      }
      
      if (fileList.value.length != 0) {
        formdata.append("file", fileList.value[0].raw);
      } else {
        formdata.append("file", null);
      }
      let ids = form.value.roles.map((item) => item.roleId);
      let names = form.value.roles.map((item) => item.roleName);
      formdata.append("allowedRoles", ids.join(","));
      formdata.append("allowedRolesName", names.join(","));
      if (titleType.value == "add") {
        //新建
        apiGptmodelPost(formdata);
      } else {
        //编辑
        formdata.append("id", rowDataId.value);
        apiGptmodelPut(formdata);
      }
    } else {
      return false;
    }
  });
}

// 创建
const apiGptmodelPost = (formdata: any) => {
  addModel(formdata)
    .then((res) => {
      proxy.$modal.msgSuccess(proxy.$t("commen.success"));
      visibleDialogClose();
      getList();
    })
    .catch((err) => {
      proxy.$modal.msgError(proxy.$t("commen.error"));
    });
}
//编辑
const apiGptmodelPut = (formdata: any) => {
  updateModel(formdata)
    .then((res: any) => {
      proxy.$modal.msgSuccess(proxy.$t("commen.success"));
      visibleDialogClose();
      getList();
    })
    .catch((err) => {
      proxy.$modal.msgError(proxy.$t("commen.error"));
    });

}
// 删除
const deleteClick = (row: any, type: any) => {
  proxy.$modal
    .confirm(proxy.$t('commen.deleteMsg'))
    .then(() => {

      let params = null;
      if (type == "arr") {
        params = row.map((item) => {
          return item.id;
        });
      } else {
        params = [row.id];
      }
      delModel(params).then((res) => {
        proxy.$modal.msgSuccess(proxy.$t("commen.success"));
        getList();
      });
    })


}
//  每页多少条
const handleSizeChange = (val: any) => {
  requestStr.value.size = val;
  getList();
}
//  分页
const handleCurrentChange = (val: any) => {
  requestStr.value.page = val;
  getList();
}
onMounted(() => {
  getList();
  apiRolesAllUnlimited();
});
</script>


<style scoped lang='scss'>
.pagevue {
  // padding: 20px 20px 60px;
}

.searchBox {
  margin-bottom: 20px;
}

.btnBox {
  margin-bottom: 20px;
}

::v-deep .el-dialog__body {
  padding: 10px 20px;
}

.upload-demo {
  margin-bottom: 12px;

  ::v-deep .el-upload-dragger {
    width: 439px;
  }

  .el-upload__tip {
    color: #f56c6c;
  }
}
</style>